#include <brpc/server.h>
#include <butil/logging.h>
#include "main.pb.h"

// 继承于EchoService创建一个子类，并实现rpc调用的业务功能
class EchoServiceImpl : public example::EchoService
{
public:
    EchoServiceImpl() {}
    ~EchoServiceImpl() {}

    virtual void Echo(::google::protobuf::RpcController *controller,
                      const ::example::EchoRequest *request,
                      ::example::EchoResponse *response,
                      ::google::protobuf::Closure *done)
    {
        brpc::ClosureGuard closure_suard(done);
        std::cout << "收到消息: " << request->message() << std::endl;

        std::string resp = "服务器回应: " + request->message();
        response->set_message(resp);
        // 不使用brpc::ClosureGuard进行管理则由done调用Run()方法来表示完成响应
        // done->Run();
    }
};

int main(int argc, char *arv[])
{
    // 关闭brpc的默认日志输出
    logging::LoggingSettings settings;
    settings.logging_dest = logging::LoggingDestination::LOG_TO_NONE;
    logging::InitLogging(settings);

    // 构造服务器对象
    brpc::Server server;
    // 向server中添加EchoService服务
    EchoServiceImpl echo_service;
    int ret = server.AddService(&echo_service, brpc::ServiceOwnership::SERVER_DOESNT_OWN_SERVICE);
    if (ret == -1)
    {
        std::cout << "添加RPC服务失败" << std::endl;
        return -1;
    }

    // 启动服务器
    brpc::ServerOptions options;
    // 连接空闲超时时间,超时后连接关闭
    options.idle_timeout_sec = -1;
    // IO线程数量
    options.num_threads = 1;
    ret = server.Start(8080, &options);
    if (ret == -1)
    {
        std::cout << "服务器启动失败" << std::endl;
        return -1;
    }

    // 等待运行结束
    server.RunUntilAskedToQuit();
    return 0;
}